package norain.wxt.controllers;


import norain.wxt.Tools.JdbcPool;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * Created by wxt on 16/4/21.
 */
@WebServlet(name = "HelloJdbc")
public class HelloJdbcPool extends HttpServlet {

    private static JdbcPool pool = new JdbcPool();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setCharacterEncoding("UTF-8");//设置将字符以"UTF-8"编码输出到客户端浏览器
        //通过设置响应头控制浏览器以UTF-8的编码显示数据，如果不加这句话，那么浏览器显示的将是乱码
        response.setHeader("content-type", "text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            Connection conn=  pool.getConnection();

            //3.获取用于向数据库发送sql语句的statement
            Statement st = conn.createStatement();

            String sql = "SELECT id,name,password,email,birthday FROM users u";
            //4.向数据库发sql,并获取代表结果集的resultset
            ResultSet rs = st.executeQuery(sql);

            //5.取出结果集的数据
            while (rs.next()) {
                out.write(("id=" + rs.getObject("id")));
                out.write("<hr/>");
                out.write(("name=" + rs.getObject("name")));
                out.write("<hr/>");
                out.write(("password=" + rs.getObject("password")));
                out.write("<hr/>");
                out.write(("email=" + rs.getObject("email")));
                out.write("<hr/>");
                out.write(("birthday=" + rs.getObject("birthday")));
                out.write("<hr/>");
            }

            //6.关闭链接，释放资源
            rs.close();
            st.close();
            conn.close();
        } catch (Exception ex) {
            out.write(("发生错误:" + ex.getMessage()));
        }
        finally {

        }
    }
}
